package System;

import java.awt.Component;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Server 
{
	/**The main frame of server*/
	public static JFrame frame;
	/**The main server's panel for login*/
	public static ServerGUI serverLogin;
	/**The main server's panel while the server is on*/
	public static ServerOnGUI serverOn;
	/**the actual server variable*/
	public static EchoServer sv;
	

	public static void terminateServer()
	{
		try{sv.close();}
		catch(Exception ex) 
		{
			JOptionPane.showMessageDialog(null,"Can't close server: "+ex.getMessage(), "System Message", JOptionPane.ERROR_MESSAGE);
			System.exit(1);
		}
		sv = null;
		serverLogin = new ServerGUI();
		setScreen(serverOn,serverLogin);
	}
	
	/**
	 * This Method remove and old component from the frame and adds the new one to it
	 * In case old Component is null only the new one will be added. also resizing the frame to the newComp sizes
	 * @param oldComp the old component to dispose
	 * @param newComp the new component to set
	 */
	private static void setScreen(Component oldComp, Component newComp)
	{		
		if (oldComp != null)
		{
			oldComp.setVisible(false);
			frame.remove(oldComp);
		}
		if (newComp != null)
		{
			frame.add(newComp);
			frame.setLocation(300,200);
			frame.setSize(newComp.getSize());
			newComp.setVisible(true);
		}
	}
	
	public static void setServer(int port, String dbPass)
	{
		try
		{
			sv = new EchoServer(port,dbPass);
			serverOn = new ServerOnGUI();
			setScreen(serverLogin,serverOn);
			sv.listen();
			
		}
		catch(Exception ex)
		{
			JOptionPane.showMessageDialog(null, "ERROR - Could not listen for clients! "+ ex.getMessage(), 
					"System Message", JOptionPane.ERROR_MESSAGE);
			System.exit(1);
		}
	}
	
	/**
	 * This method is responsible for the creation of 
	 * the server instance using the server gui for getting the details about connection.
	 *
	 */
	public static void main(String[] args) 
	{
		frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		serverLogin = new ServerGUI();
		frame.setVisible(true);
		setScreen(null,serverLogin);
	}
}
